import pandas as pd
import csv
import os
from IPython import embed
from git import Repo
from mailing import send_mail_cse_smtp
from collections import defaultdict
from sys import argv
import traceback
import logging


def gen_link_mail(sid):
    if len(sid) != 10:
        raise RuntimeError("Wrong SID {}".format(sid))
    return sid + "@link.cuhk.edu.hk"


def get_current_cmt_info(code_dir):
    # make sure all branches exist locally!
    repo = Repo(code_dir)

    branches = sorted(list(repo.refs), key=lambda x: x.commit.authored_datetime)
    branch = branches[-1]
    latest_branch_name = branch.name
    latest_cmt = branch.commit

    return latest_branch_name, latest_cmt


def get_latest_main_cmt(code_dir):
    repo = Repo(code_dir)

    branch_list = []
    for branch_name in branches:
        try:
            commits = list(repo.iter_commits(branch_name))
            latest_cmt_before_ddl = sorted(
                [
                    cmt
                    for cmt in commits
                    if str(cmt.authored_datetime).split("+")[0] <= ddl
                ],
                key=lambda x: x.authored_datetime,
            )[-1]

            branch_list.append((branch_name, latest_cmt_before_ddl))
            break
        except Exception as e:
            # print(traceback.format_exc())
            # print("No branch [{}]".format(branch_name))
            pass

    if not branch_list:
        print("No main/master branch found in {}".format(code_dir))
        return "", ""

    branch_list = sorted(branch_list, key=lambda x: x[1].authored_datetime)
    latest_branch_name, latest_cmt = branch_list[-1]

    return latest_branch_name, latest_cmt


ddl = "2021-05-02 23:59:59"  # only consider cmt before the ddl
branches = [
    "final_submission",
    "main",
    "master",
    "combined",
    "develop",
]  # only consider branches in this range
n_students = 5  # how many students in one team


phase = "Final Report and Commented Code"
subject = "CSCI3100 Project Final Commented Code Submission Notice"

text = """Dear Group {},

We have pulled the latest code from your GitHub repository. Below is the submission detail.

Project Name: {}
Porject Repository: {}
Phase: {}
Branch : {}
Commit Hash: {}
Commit Time: {}

Regards,
CSCI3100 TA Group"""


group_prefix = ""  # for TA use

if __name__ == "__main__":
    group_info = pd.read_csv("./final-group.csv")

    gid_projname = dict(zip(group_info["Group ID"], group_info["Project Name"]))
    gid_url = dict(zip(group_info["Group ID"], group_info["URL"]))

    group_addr_dict = defaultdict(list)
    for idx, row in group_info.iterrows():
        for i in range(1, n_students + 1):
            sid = row["SID{}".format(i)]
            try:
                sid = str(int(sid))
                group_addr_dict[row["Group ID"]].append(gen_link_mail(sid))
            except:
                print("Fail")

    error_groups = []
    records = []
    count = 0
    for gid in group_info["Group ID"]:
        if group_prefix and not gid.startswith(group_prefix):
            continue
        print("Sending to {}".format(gid))
        receiver_list = group_addr_dict[gid]
        receiver_list.append("jyliu@cse.cuhk.edu.hk")
        code_dir = "./final_codes/group_{}".format(gid)
        branch_name, cmt = get_current_cmt_info(code_dir)
        # branch_name, cmt = get_latest_main_cmt(code_dir)
        if not cmt:
            error_groups.append(gid)
            continue
        msg = text.format(
            gid,  # group id
            gid_projname[gid],
            gid_url[gid],
            phase,
            branch_name,  # branch name
            cmt.hexsha,  # hash
            cmt.authored_datetime,  # cmt time
        )

        records.append(
            {
                "GroupID": gid,
                "ProjectName": gid_projname[gid],
                "BranchName": branch_name,
                "CommitDate": cmt.authored_datetime,
                "Commit": cmt.hexsha,
                "URL": gid_url[gid],
            }
        )

        # receiver_list = ["jyliu@cse.cuhk.edu.hk"]

        # uncomment it to send emails
        send_mail_cse_smtp(
            "csci3100",  # cse username
            subject,  # subject
            msg,  # content
            None,  # no attachment
            receiver_list,  # receiver list
        )
        count += 1

        print("Sent to \n {}".format(receiver_list))
        print("\n" + subject)
        print(msg)
        print("-" * 20)

    pd.DataFrame(records).to_csv("{}_records.csv".format(phase), index=False)
    print("Done for {} teams.".format(count))
    print("Failed fot {}.".format(error_groups))